package com.wj.wjpicturebackend.manager.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import com.wj.wjpicture.application.service.PictureApplicationService;
import com.wj.wjpicture.infrastructure.config.RabbitMqConfig;
import com.wj.wjpicture.infrastructure.api.CosManager;

import com.wj.wjpicture.interfaces.dto.picture.PictureTaskMessage;
import com.wj.wjpicture.domain.picture.entity.Picture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Component
public class ThumbnailConsumer {

    @Resource
    private CosManager cosManager;

    @Resource
    private PictureApplicationService pictureApplicationService;

    /**
     * 处理缩略图生成任务
     */
    @RabbitListener(queues = RabbitMqConfig.THUMBNAIL_QUEUE)
    public void handleThumbnailTask(PictureTaskMessage message, Channel channel, Message msg) throws IOException {
        long deliveryTag = msg.getMessageProperties().getDeliveryTag(); // 消息唯一标识
        InputStream objectContent = null;
        FileOutputStream outputStream = null;
        try {
            log.info("开始处理缩略图生成，pictureId: {}", message.getPictureId());

            // 1. 从COS下载原图到本地临时文件
            String originalUrl = message.getOriginalUrl();
            String key = originalUrl.replace(cosManager.cosClientConfig.getHost() + "/", ""); // 提取COS的key

            // 创建临时文件
            File tempFile = File.createTempFile("thumbnail_", "." + message.getFileSuffix());

            // 正确的文件下载方式：使用输入流和输出流
            objectContent = cosManager.getObject(key).getObjectContent();
            outputStream = new FileOutputStream(tempFile);

            // 缓冲读取并写入文件
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = objectContent.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();

            // 2. 生成缩略图（调用COS的图片处理接口）
            String thumbnailKey = "thumbnail/" + message.getPictureId() + "_small." + message.getFileSuffix();
            cosManager.putPictureObject(thumbnailKey, tempFile); // 上传缩略图到COS

            // 3. 更新数据库中的缩略图URL
            Picture picture = new Picture();
            picture.setId(message.getPictureId());
            picture.setThumbnailUrl(cosManager.cosClientConfig.getHost() + "/" + thumbnailKey);
            pictureApplicationService.updateById(picture);

            log.info("缩略图生成完成，pictureId: {}", message.getPictureId());
            // 手动确认消息（RabbitMQ删除该消息）
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("缩略图生成失败，pictureId: {}", message.getPictureId(), e);
            // 处理失败：拒绝消息并重新入队（最多重试3次，超过则进入死信队列）
            channel.basicNack(deliveryTag, false, true);
        } finally {
            // 确保流被关闭
            if (objectContent != null) {
                try {
                    objectContent.close();
                } catch (IOException e) {
                    log.error("关闭输入流失败", e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流失败", e);
                }
            }
        }
    }
}
